package main

import (
	"bufio"
	"context"
	"fmt"
	"io"
	"net/http"
	"os"
	"path"
	"sync"
)

//下载符合要求的图片

type Image struct {
	imageUrl string
}

type ImageDealer struct {
	folder string
	group  *sync.WaitGroup
}

type ImgDealerManager struct {
	Manager
	folder string
}

func NewImgDealerManager() *ImgDealerManager {
	return &ImgDealerManager{}
}

func (m *ImgDealerManager) SetFolder(folder string) {
	m.folder = folder
	for _, dealer := range m.dealers {
		imgDealer, ok := dealer.(*ImageDealer)
		if !ok {
			fmt.Println("Wrong dealer")
			return
		}
		imgDealer.folder = folder
	}
}

func NewImage(url string) *Image {
	return &Image{
		imageUrl: url,
	}
}

func NewImageDealer(group *sync.WaitGroup) *ImageDealer {
	return &ImageDealer{group: group}
}

func (dealer *ImageDealer) Run(ctx context.Context) {
	dealer.group.Add(1)
	for {
		select {
		case <-ctx.Done():
			defer dealer.group.Done()
			return
		case img := <-ImageContainer:
			dealer.DownLoadImage(img)
		}
	}
}

func (dealer *ImageDealer) DownLoadImage(img *Image) {
	fmt.Println("DownLoading Image,", img.imageUrl)
	resp, err := http.Get(img.imageUrl)
	if err != nil {
		fmt.Println("ERROR!DownLoad ERROR")
		return
	}
	reader := bufio.NewReader(resp.Body)

	fileName := path.Base(img.imageUrl)
	file, err := os.Create(dealer.folder + fileName)
	if err != nil {
		fmt.Println("ERROR!Create File Error,", err)
		return
	}
	writer := bufio.NewWriter(file)

	written, err := io.Copy(writer, reader)
	if err != nil {
		fmt.Println("ERROR! Write file err,", err)
		return
	}
	fmt.Printf("Write success,fileName is %s,size is %d", fileName, written)

}
